<?php
/**
 * Modelo CRUD de usuários
 * @author Wiliame Morais @ PC4 Team
 */
class PC4_Crud_Blog extends PC4_Crud_Upload2{
	
	function __construct($caminho = '', $tabela = 'posts_blog', $validacoes = array('imagem' => array('tamMaximo' => 2048))) {
			
		parent::__construct($caminho, $tabela, $validacoes);
		
		$tabelas = array(
			'post_rel_tags prt' => array(
										'pk' => 'p.id',
										'fk' => 'prt.id_post',
										'join' => 'LEFT'
			), 
			'tags t' => array(
							'pk'=> 't.id',
							'fk' => 'prt.id_tags',
							'join' => 'LEFT'
			),
			'comentarios_posts cp' => array(
										'pk' => 'p.id',
										'fk' => 'cp.id_post AND `cp`.`ativo` = 1',
										'join' => 'LEFT'
			), 
			'usuarios u' => array(
							'pk'=> 'p.id',
							'fk' => 'p.id_usuario',
							'join' => 'LEFT'
			)
		);		
		$this->mTabelas = new PC4_Crud_Tabelas('posts_blog', $tabelas);
	}			

	public function lista($pagina, $limite, $debug){
		$this->db->select("p.*, DATE_FORMAT(p.registro, '%d/%m/%Y %H:%i') AS data, u.nome AS nomeUsuario, COUNT(DISTINCT cp.id) as numComentarios, GROUP_CONCAT(DISTINCT t.tag SEPARATOR ' ') AS tags, GROUP_CONCAT(DISTINCT t.id SEPARATOR ' ') AS tagsId", false);
		$this->db->group_by("p.id");
		return $this->mTabelas->lista($pagina, $limite, $debug);
	}
	
	public function insere($campos){
		$tags = $campos['palavras_selecionadas'];
		unset($campos['palavras_selecionadas']);
		$idInserido = parent::insere($campos);
		$this->salvaTags($idInserido, $tags);
		return $idInserido;
	}
	
	function salvaTags($id_post, $tags) {
		$this->db->delete('post_rel_tags', 'id_post = '.$id_post);
		if (!empty($tags)) {
			foreach ($tags as $c => $v) {
				$campos[] = "($id_post, ". trim($v). ")";
			}
			$sql = "INSERT INTO post_rel_tags
					(
					    id_post,
					    id_tags
					)
					VALUES ".implode(',', $campos);
			$this->db->query($sql);

		}
	}
}
?>